package getOffer.offer29;

/**
 * @Author: wjy
 * @Date: 2021/11/27 11:02
 */
public class Solution {

    public static void main(String[] args) {

        // 1 2 3
        // 4 5 6
        // 7 8 9

        int[][] ints = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

        Solution solution = new Solution();
        int[] nums = solution.spiralOrder(ints);

        for (int i : nums) {
            System.out.println(i);
        }


    }

    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) {
            return new int[0];
        }
        int[] res = new int[matrix.length * matrix[0].length];

        int index = 0;

        int t = 0, l = 0;

        int r = matrix[0].length - 1;
        int b = matrix.length - 1;

        while (true) {
            // left -> right
            for (int i = l; i <= r; i++) {
                res[index++] = matrix[t][i];
            }
            if (++t > b) {
                break;
            }
            // top -> bottom
            for (int j = t; j <= b; j++) {
                res[index++] = matrix[j][r];
            }
            if (--r < l) {
                break;
            }
            // right -> left
            for (int m = r; m >= l; m--) {
                res[index++] = matrix[b][m];
            }
            if (--b < t) {
                break;
            }
            // bottom -> top
            for (int n = b; n >= t; n--) {
                res[index++] = matrix[n][l];
            }
            if (++l > r) {
                break;
            }

        }

        return res;
    }

}